import React, { useEffect, useRef } from 'react';
import * as echarts from 'echarts/core';
import { BarChart } from 'echarts/charts';
import { TitleComponent, TooltipComponent } from 'echarts/components';
import { CanvasRenderer } from 'echarts/renderers';
import { PieChart } from 'echarts/charts';
import { ToolboxComponent } from 'echarts/components';

import {
    GridComponent,
    DatasetComponent,
    LegendComponent
} from 'echarts/components';

echarts.use([
    GridComponent,
    TitleComponent,
    TooltipComponent,
    DatasetComponent,
    LegendComponent,
    BarChart,
    CanvasRenderer
]);

echarts.use([TitleComponent, TooltipComponent, BarChart, CanvasRenderer, PieChart, ToolboxComponent]);

const EChartsComponent = () => {
    const chartRef = useRef(null);
    const chartInstance = useRef(null); // 用于存储图表实例

    useEffect(() => {
        const chart = echarts.init(chartRef.current);

        // 初始化图表实例
        chartInstance.current = chart;

        const option = {
            legend: {
                top: 'bottom'
            },
            toolbox: {
                show: true,
                feature: {
                    mark: { show: true },
                    dataView: { show: true, readOnly: false },
                    restore: { show: true },
                    saveAsImage: { show: true }
                }
            },
            series: [
                {
                    name: 'Nightingale Chart',
                    type: 'pie',
                    radius: [25, 100],
                    center: ['50%', '50%'],
                    roseType: 'area',
                    itemStyle: {
                        borderRadius: 5
                    },
                    data: [
                        { value: 70, name: '头颈外科' },
                        { value: 58, name: '其他科' },
                        { value: 132, name: '内镜科' },
                        { value: 100, name: '口腔科' },
                        { value: 158, name: '肛肠科' },
                        { value: 86, name: '中西医科' },
                        { value: 82, name: '妇科' },
                        { value: 98, name: '呼吸道感染科' }
                    ]
                }
            ]
        };
        chart.setOption(option);
        // 监听容器大小变化
        const resizeObserver = new ResizeObserver(() => {
            chart.resize();
        });
        resizeObserver.observe(chartRef.current);

        return () => {
            chart.dispose();
            resizeObserver.disconnect();
        };
    }, []);

    return <div ref={chartRef} style={{ width: '40vw', height: '300px', maxWidth: '40vw', maxHeight: '300px' }}></div>;
};

export default EChartsComponent;

